using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Admin.NET.Application.Entity;
using SqlSugar;

namespace Admin.NET.Application;

public static class CommonUtils
{
	public static async Task<List<long>> GetBuildingIds(ISqlSugarClient db, long? buildingId, bool isIncludeSub)
	{
		List<long> buildingIds = new List<long>();
		if (buildingId.HasValue && isIncludeSub)
		{
			List<Building> allbuilding = await db.Queryable<Building>().ToListAsync();
			List<Building> root = allbuilding.Where((Building w) => w.Id == buildingId).ToList();
			foreach (Building item in root)
			{
				MapChild(item, allbuilding, buildingIds);
			}
		}
		return buildingIds;
	}

	public static void MapChild(Building item, List<Building> list, List<long> ids)
	{
		if (ids.Contains(item.Id))
		{
			return;
		}
		ids.Add(item.Id);
		item.Children = new List<Building>();
		List<Building> children = list.Where((Building w) => w.Pid == item.Id).ToList();
		if (children.Count <= 0)
		{
			return;
		}
		item.Children.AddRange(children);
		foreach (Building child in children)
		{
			MapChild(child, list, ids);
		}
	}
}
